var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var app = getApp();

Page({
  data: {
    dataLoaded: false,
    isLogin: false,
    userInfo: {},
    loginPanel: {
      yzmTime: 0,
      phone: '',
      yzm: '',
    },
  },
  // 事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    var that = this

    app.getUserInfo(function (userInfo) {
      that.setData({
        isLogin: !!app.getUserSid(),
        userInfo: userInfo,
        dataLoaded: true,
      });
    })
  },

  onShow() {
    this.setData({
      isLogin: !!app.getUserSid(),
    });
  },

  /**
   * 手机号输入
   */
  _phoneInput: function (evt) {
    var panel = this.data.loginPanel;

    panel.phone = evt.detail.value;
    this.setData({ panel });
  },

  /**
   * 验证码输入
   */
  _yzmInput: function (evt) {
    var panel = this.data.loginPanel;

    panel.yzm = evt.detail.value;
    this.setData({ panel });
  },

  /**
   * 获取验证码
   */
  _getYzm() {
    if (!this.data.panel.phone) {
      return util.alert('请输入手机号');
    }
    ajax.P('/openapi/CBrand/sendMsg2', {
      phone: this.data.panel.phone,
    }, function (data) {
      this._timerDown(60);
    }.bind(this));
  },

  /**
   * 倒计时
   */
  _timerDown: function (time) {
    var panel = this.data.loginPanel;

    panel.yzmTime = --time;
    this.setData({ loginPanel: panel });

    if (panel.yzmTime == 0) {
      return;
    }
    setTimeout(function () {
      this._timerDown(time);
    }.bind(this), 1000);
  },

  /**
   * 登陆
   */
  _login() {
    var self = this;
    var loginPanel = this.data.loginPanel;

    ajax.P('/openapi/CBrand/bandPhone2', {
      code: loginPanel.yzm,
      phone: loginPanel.phone,
      openId: app.getOpenId(),
    }, function (data) {
      var userSid = data.result.userSid;

      app.setUserSid(userSid);
      self.setData({ isLogin: !!userSid });
    });
  }
});